package com.example.clientend.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 调用向日葵SDK进行向日葵远控服务注册和注销的工具类
 */
@Component
@Slf4j
public class BatFileHandler {
    // 服务注册bat文件快捷方式的路径
    @Value("${path.installServicePath}")
    private String installPath;
    // 服务注销bat文件快捷方式的路径
    @Value("${path.uninstallServicePath}")
    private String unstallPath;
    
    // 会话信息输出日志txt文件路径
    @Value("${path.serviceLogPath}")
    private String logPath;
    // bat文件所在目录
    @Value("${path.sdkPath}")
    private String sdkPath;

    /**
     * 向日葵远控服务注册
     */
    public void installService(){
        // 清除会话信息输出日志
        clearLog();
        try {
            // 获取InstallService.bat的快捷方式的绝对路径
            String installSdkPath = getBatFileAbsolutePath("install");
            // 创建ProcessBuilder对象并设置命令参数
            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", installSdkPath);
            processBuilder.redirectErrorStream(true);

            // 获取进程并等待其完成
            Process process = processBuilder.start();
            
            // 消费输出流，避免缓存区满了之后线程阻塞
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
            String line;
            while ((line = reader.readLine()) != null){
                log.info(line);
            }
            reader.close();
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                log.info("远控服务注册bat文件调用成功！");
            } else {
                log.info("远控服务注册bat文件调用失败！");
            }
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向日葵远控服务注销
     */
    public void uninstallService(){
        try {
            // 获取UnstallService.bat的快捷方式的绝对路径
            String uninstallSdkPath = getBatFileAbsolutePath("uninstall");
            // 创建ProcessBuilder对象并设置命令参数
            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", uninstallSdkPath);
            processBuilder.redirectErrorStream(true);

            // 获取进程并等待其完成
            Process process = processBuilder.start();

            // 消费输出流，避免缓存区满了之后线程阻塞
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"gbk"));
            String line;
            while ((line = reader.readLine()) != null){
                log.info(line);
            }
            reader.close();
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                log.info("远控服务注销bat文件调用成功！");
            } else {
                log.info("远控服务注销bat文件调用失败！");
            }
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清空log文件中的信息
     */
    public void clearLog(){
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(logPath))) {
            writer.write(""); // 将写入的内容设置为空字符串，相当于清空了原有内容
//            System.out.println("成功清空txt文件的内容！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 正则表达式匹配文件名，获取InstallService.bat和UnstallService.bat的快捷方式的绝对路径
     */
    public String getBatFileAbsolutePath(String workType){
        File folder = new File(sdkPath);
        // 遍历文件夹下的文件
        File[] files = folder.listFiles();
        if (files != null) {
            Pattern pattern = null;
            if (workType.equals("install")){
                pattern = Pattern.compile(".*InstallService.*\\.lnk");
            }
            if (workType.equals("uninstall")){
                pattern = Pattern.compile(".*UnstallService.*\\.lnk");
            }
            try {
                for (File file : files) {
                    // 判断是否是文件
                    if (file.isFile()) {
                        String fileName = file.getName();
                        // 正则表达式匹配文件名
                        Matcher matcher = pattern.matcher(fileName);
                        if (matcher.find()){
                            // 返回绝对路径
                            return file.getCanonicalPath();
                        }
                    }
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
